<template>
  <div class="koi-navigation <md:hidden">
    <ul class="menu black_color">
      <!-- 一级菜单 class="menu-item-has-children" -->
      <li v-for="(item, index) in topLevelMenus" :key="item.meta?.menuId || index">
        <a
          class="dark:text-#D8D8D8 transition-all duration-600 transition-ease"
          @click="handleTopMenuClick(item)"
          :class="[activeTopMenuId == item.meta?.menuId ? '!text-[--el-color-primary]' : '']"
          >{{ getMenuLanguage(item.meta?.title) }}
          <el-icon class="align-middle" :size="13" v-if="item?.children">
            <ArrowDown />
          </el-icon>
        </a>
        <!-- 二级菜单 -->
        <ul class="!m-t-11px !dark:bg-#3A3A3A" v-if="item?.children && item?.children.length > 0">
          <li class="!p-x-6px !m-b-4px" v-for="child in item.children" :key="child.path" @click="handleMenuRouter(child)">
            <a
              class="!hover:text-[--el-color-primary] !rounded-4px hover:bg-[rgb(245,245,245)] dark:hover:bg-[rgb(245,245,245,0.07)] transition-all duration-600 transition-ease"
              :style="{
                color: child.path == route.path ? 'var(--el-color-primary)' : '',
                background: child.path == route.path ? 'var(--el-color-primary-light-9)' : ''
              }"
            >
              <span
                class="dark:text-#D8D8D8"
                :class="[child.path == route.path ? '!dark:text-[--el-color-primary]' : '']"
                style="font-family: &quot;Open Sans&quot;, sans-serif"
                >{{ getMenuLanguage(child.meta?.title) }}</span
              >
            </a>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import useAuthStore from "@/stores/modules/auth.ts";
import { getMenuLanguage } from "@/utils/index.ts";
import { koiMsgError } from "@/utils/koi.ts";
import { HOME_URL } from "@/config/index.ts";

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

// 获取所有顶级菜单[第一层级]
const topLevelMenus = computed(() => authStore.showMenuList.filter((item: any) => item.meta?.isHide == "1"));

// 当前激活的顶级菜单ID
const activeTopMenuId = ref<any>();
// 当前显示的子菜单树[包含所有层级]
const currentSubMenuTree = ref<any[]>([]);
// 当前激活的子菜单路径
// const activeMenu = computed(() => (route.meta?.activeMenu ? route.meta?.activeMenu : route.path) as string);

/** 递归检查菜单项是否匹配 */
const containsActiveMenu = (menu: any, activeMenu: string): boolean => {
  // 检查当前菜单是否匹配
  if (menu.path == String(activeMenu)) {
    return true;
  }

  // 递归检查子菜单
  if (menu.children && menu.children.length > 0) {
    for (const child of menu.children) {
      if (containsActiveMenu(child, activeMenu)) {
        return true;
      }
    }
  }
  return false;
};

/**
 * @description 查找最顶级菜单对象
 * @param routes 菜单递归数据
 * @param activeMenu 选中路由 或 menuId
 */
const findMenuByActiveMenu = (routes: any[], activeMenu: any) => {
  // 遍历所有顶级菜单
  for (const route of routes) {
    // 检查当前顶级菜单是否匹配
    if (route.path == String(activeMenu)) {
      return route;
    }

    // 检查子菜单是否包含匹配项
    if (route.children && route.children.length > 0) {
      if (containsActiveMenu(route, activeMenu)) {
        return route;
      }
    }
  }

  return null; // 未找到匹配项
};

/**
 * @description 根据 menuId 查找顶级父菜单（排除自身）
 * @param routes 菜单数据[无限层级结构]
 * @param menuId 要查找的菜单 ID
 * @returns 顶级父菜单对象，未找到或目标菜单是顶级菜单时返回 null
 */
const findTopMenuByMenuId = (routes: any[], targetMenuId: any): any => {
  // 转换目标菜单ID为字符串
  const targetId = String(targetMenuId);

  // 创建菜单ID到菜单对象的映射
  const menuMap = new Map();

  // 递归构建菜单映射并添加父菜单关系
  const buildMenuMap = (menuList: any, parentId?: any) => {
    for (const menu of menuList) {
      if (menu.meta?.menuId) {
        const menuId = String(menu.meta.menuId);

        // 添加父菜单关系
        menu.parentId = parentId;
        menuMap.set(menuId, menu);
      }

      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        const currentParentId = menu.meta?.menuId ? String(menu.meta.menuId) : parentId;
        buildMenuMap(menu.children, currentParentId);
      }
    }
  };

  // 构建映射
  buildMenuMap(routes);

  // 检查菜单是否存在
  if (!menuMap.has(targetId)) {
    return null;
  }

  // 查找顶层菜单的递归函数
  const findTopMenu: any = (menuId: any) => {
    const menu = menuMap.get(menuId);

    // 如果菜单没有父菜单或自身就是顶级菜单，返回null
    if (!menu.parentId) {
      return null;
    }

    // 递归查找父菜单的顶层菜单
    const parentTopMenu = findTopMenu(menu.parentId);

    return parentTopMenu || menuMap.get(menu.parentId);
  };

  // 查找目标菜单的顶层菜单
  return findTopMenu(targetId);
};

/**
 * 根据顶级菜单ID获取其完整的子菜单树
 * @param {number|string} topMenuId 顶级菜单ID
 * @returns {Array} 完整的子菜单树
 */
const getSubMenuTree = (topMenuId: number | string) => {
  const topMenu = topLevelMenus.value.find((item: any) => item.meta.menuId === topMenuId);
  return topMenu?.children || [];
};

/**
 * 点击顶级菜单处理
 * @param {Object} item 菜单项
 */
const handleTopMenuClick = (route: any) => {
  if (route.meta?.isLink) {
    if (/^https?:\/\//.test(route.meta?.isLink)) {
      return window.open(route.meta.isLink, "_blank");
    } else {
      koiMsgError("错误链接地址，禁止跳转");
      return;
    }
  }

  if (!route?.children) {
    // 更新当前激活的顶级菜单
    activeTopMenuId.value = route.meta?.menuId;
    currentSubMenuTree.value = [];
    router.push({
      path: route.path || HOME_URL
    });
    return;
  }

  // 更新当前激活的顶级菜单
  activeTopMenuId.value = route.meta?.menuId;

  // 获取该顶级菜单的子菜单树
  currentSubMenuTree.value = getSubMenuTree(route.meta?.menuId);
};

/**
 * 初始化菜单状态
 */
const initMenu = () => {
  if (!topLevelMenus.value.length) return;

  const { menuId, activeMenu } = route.meta || {};

  // 情况一：没有提供 menuId 或 activeMenu，默认选第一个顶级菜单
  if (!menuId && !activeMenu) {
    activeTopMenuId.value = topLevelMenus.value[0];
    return;
  }

  // 情况二：menuId 存在，activeMenu 不存在
  if (menuId && !activeMenu) {
    const topLevelMenu: any = findTopMenuByMenuId(authStore.showMenuList, String(menuId));

    if (!topLevelMenu) {
      // 未找到父级，说明是顶级菜单，直接赋值
      activeTopMenuId.value = menuId;
      currentSubMenuTree.value = [];
    } else {
      // 找到父级，设置为激活项，并加载子菜单
      activeTopMenuId.value = topLevelMenu.meta?.menuId;
      currentSubMenuTree.value = getSubMenuTree(activeTopMenuId.value);
    }

    router.push(route.path); // 同步路径
    return;
  }

  // 情况三：activeMenu 存在通过 activeMenu 查找父级菜单
  if (activeMenu) {
    const topLevelMenu: any = findMenuByActiveMenu(authStore.showMenuList, activeMenu);

    if (topLevelMenu) {
      activeTopMenuId.value = topLevelMenu.meta?.menuId;
      currentSubMenuTree.value = getSubMenuTree(activeTopMenuId.value);
      router.push(route.path);
    } else {
      koiMsgError("The menu data configuration is error");
    }
  }
};

onMounted(() => {
  initMenu();
});

// 监听路由变化
watch(
  () => route,
  () => {
    initMenu();
  },
  { deep: true }
);

/** 打开标签页 或 外部链接 */
const handleMenuRouter = (row: any) => {
  if (row.meta?.isLink) {
    if (/^https?:\/\//.test(row.meta?.isLink)) {
      return window.open(row.meta.isLink, "_blank");
    } else {
      koiMsgError("错误链接地址，禁止跳转");
      return;
    }
  }

  router.push(row.path);
};
</script>

<style scoped>
/* .themelazer_main_header .themelazer_middle_header {
  position: relative;
  top: 0;
  background: #000;
}
.themelazer_main_header .themelazer_middle_header.white_bg {
  position: relative;
  top: 0;
  background: #fff;
  color: #000;
  border: 1px solid #f2f1f1;
  z-index: 999 !important;
}
.themelazer_main_header .themelazer_middle_header .container {
  padding: 10px;
  padding-right: 20px;
  padding-left: 20px;
}
.themelazer-nav {
  width: 100%;
  position: absolute;
}

.koi-navigation .themelazer_navigation_hide {
  opacity: 0;
  visibility: hidden;
} */

.koi-navigation {
  text-align: center;
  color: #161616;
  font-size: 12px;
  font-weight: 500;
  letter-spacing: 0.09em;
  text-transform: uppercase;
  -webkit-font-smoothing: subpixel-antialiased;
}

.koi-navigation ul {
  list-style: none;
  position: relative;
  margin: 0px;
  padding: 0px;
}

.koi-navigation ul li {
  display: inline-block;
  float: none;
  vertical-align: top;
}

.koi-navigation .menu li > a {
  float: left;
  padding: 0;
  color: inherit;
  font-family: "Open Sans", sans-serif;
}

.koi-navigation .menu > li {
  padding: 0px 10px;
}
.koi-navigation .menu > li > a.black_color {
  padding: 0px;
  height: 60px;
  line-height: 60px;
  color: #000;
  @apply dark:text-#D8D8D8;
  position: relative;
  font-weight: 600;
}
.koi-navigation .menu.black_color > li > a {
  padding: 0px;
  height: 50px;
  line-height: 50px;
  color: #000;
  @apply dark:text-#D8D8D8;
  position: relative;
  font-weight: 600;
  margin: 0;
  padding: 0;
  display: inline;
  background-repeat: no-repeat;
  box-sizing: border-box;
}

.koi-navigation .menu.black_color > li > a:hover {
  background-size: 100% 1px;
  color: var(--el-color-primary);
}

.koi-navigation .menu > li > a {
  padding: 0px;
  height: 50px;
  line-height: 50px;
  /* color: #fff; */
  position: relative;
  font-weight: 800;
}
.koi-navigation .menu > li > a:before {
  background-color: #fff;
  height: 1px;
  left: 0;
  right: 0px;
  opacity: 0;
  pointer-events: none;
  position: absolute;
  top: 39px;
  -webkit-transform: translateY(1px);
  transform: translateY(1px);
  -webkit-transition: all 0.15s cubic-bezier(0.39, 0.575, 0.565, 1);
  transition: all 0.15s cubic-bezier(0.39, 0.575, 0.565, 1);
  -webkit-transition-property:
    opacity,
    -webkit-transform;
  transition-property:
    opacity,
    -webkit-transform;
  transition-property: opacity, transform;
  transition-property:
    opacity,
    transform,
    -webkit-transform;
  content: "";
}

.koi-navigation .menu > li:first-child {
  margin-left: -21px;
}

.koi-navigation .menu-item-has-children > a:after {
  display: inline-block;
  content: "▼";
  margin-left: 3px;
  font-style: normal;
  font-weight: normal;
  font-size: 10px;
  line-height: 0.9;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
}

/* Hover and active states */
.koi-navigation .menu > li:hover > a:before,
.koi-navigation .menu > .current-menu-item > a,
.koi-navigation .menu > .current-menu-parent > a,
.koi-navigation .menu > .current-menu-ancestor > a {
  opacity: 1;
  -webkit-transform: translateY(-3px) translateZ(0);
  transform: translateY(-3px) translateZ(0);
  color: var(--el-color-primary);
}

.koi-navigation li:hover > a:after,
.koi-navigation .current-menu-item > a:after,
.koi-navigation .current-menu-parent > a:after,
.koi-navigation .current-menu-ancestor > a:after {
  color: inherit;
}

.koi-navigation .menu > li > ul,
.koi-navigation .menu > li > .sub-menu {
  top: 100%;
  margin-left: 0px;
  margin-top: -1px;
}

.koi-navigation .menu > li > ul {
  -webkit-box-shadow: 0 5px 40px rgba(0, 0, 0, 0.15);
  -moz-box-shadow: 0 5px 40px rgba(0, 0, 0, 0.15);
  box-shadow: 0 5px 40px rgba(0, 0, 0, 0.15);
  padding: 10px 0px;
}

.koi-navigation .menu li li {
  display: block;
}

.koi-navigation .menu > li:hover li a {
  pointer-events: auto;
}
.koi-navigation .menu > li li a {
  font-family: "Open Sans", sans-serif;
  float: none;
  position: relative;
  font-weight: 600;
  margin: 0;
  border-bottom: 1px dashed #eaeaea;
  text-align: left;
  display: block;
  text-decoration: none;
  padding: 5px 22px;
  font-size: 13px;
  letter-spacing: 0;
  color: #000;
  pointer-events: none;
  text-transform: capitalize;
}

.koi-navigation .menu ul li,
.koi-navigation .menu .sub-menu li {
  float: none;
  min-width: 200px;
  max-width: 350px;
  border-top: 0;
  padding: 0;
  position: relative;
}

.koi-navigation .menu > li li:first-child > a {
  border-top: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
}

.koi-navigation .sub-menu li:first-child > .sub-menu {
  margin-top: -1px;
}

.koi-navigation .menu ul,
.koi-navigation .menu .sub-menu {
  position: absolute;
  overflow: visible;
  visibility: hidden;
  display: block;
  opacity: 0;
  padding: 0;
  background: #fff;
  -webkit-transition: all 0.15s ease-in;
  transition: all 0.15s ease-in;
  z-index: 110;
  line-height: 1.8666;
}

.koi-navigation .menu ul ul {
  left: 100%;
  top: 0;
  margin-left: 0;
}

.koi-navigation li:hover > ul,
.koi-navigation li:hover > .sub-menu {
  visibility: visible;
  opacity: 1;
  pointer-events: auto;
}

.koi-navigation .menu li li:hover > a,
.koi-navigation .menu li li.current-menu-item > a {
  color: var(--el-color-primary);
}
</style>
